package com.example.timer_show;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Color;
import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class OverlayService extends Service {
    private WindowManager windowManager;
    private View overlayView;
    private boolean is24HourFormat = true;
    private Timer timer;
    private WindowManager.LayoutParams params;
    
    private int initialX;
    private int initialY;
    private float initialTouchX;
    private float initialTouchY;
    private boolean isMoving = false;
    private static final int RESIZE_HANDLE_SIZE = 40;
    private static final int MIN_WIDTH = 100;
    private static final int MIN_HEIGHT = 50;
    private static final int MAX_WIDTH = 1000;
    private static final int MAX_HEIGHT = 500;
    private float lastTouchX;
    private float lastTouchY;
    private static final int DOUBLE_TAP_TIMEOUT = 300; // 双击超时时间(毫秒)
    private static final int TOUCH_SLOP = 10; // 最小移动阈值
    private static final int DEFAULT_WIDTH = 300; // 默认宽度
    private static final int DEFAULT_HEIGHT = 150; // 默认高度
    
    private long lastTapTime = 0;
    private int screenWidth;
    private int screenHeight;
    private boolean hasMoved = false;
    private int textColor = Color.WHITE;
    private int bgColor = Color.BLACK;
    private int bgAlpha = 128;
    private String timeFormat = "HH:mm:ss";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        
        // 获取屏幕尺寸
        android.view.Display display = windowManager.getDefaultDisplay();
        android.graphics.Point size = new android.graphics.Point();
        display.getSize(size);
        screenWidth = size.x;
        screenHeight = size.y;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            timeFormat = intent.getStringExtra("timeFormat");
            if (timeFormat == null) {
                timeFormat = "HH:mm:ss"; // 设置默认格式
            }
            textColor = intent.getIntExtra("textColor", Color.WHITE);
            bgColor = intent.getIntExtra("bgColor", Color.BLACK);
            bgAlpha = intent.getIntExtra("bgAlpha", 128);
        }

        if (overlayView == null) {
            createOverlay();
        } else {
            updateColors();
            // 更新时间格式
            startTimeUpdate();
        }

        return START_STICKY;
    }

    private void createOverlay() {
        params = new WindowManager.LayoutParams(
                DEFAULT_WIDTH,  // 使用默认宽度
                DEFAULT_HEIGHT, // 使用默认高度
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
        );
        params.gravity = Gravity.TOP | Gravity.START;
        params.x = (screenWidth - DEFAULT_WIDTH) / 2;  // 居中显示
        params.y = 100;

        overlayView = LayoutInflater.from(this).inflate(R.layout.overlay_layout, null);
        TextView timeText = overlayView.findViewById(R.id.overlayTimeText);
        
        overlayView.setOnTouchListener((view, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    initialX = params.x;
                    initialY = params.y;
                    initialTouchX = lastTouchX = event.getRawX();
                    initialTouchY = lastTouchY = event.getRawY();
                    hasMoved = false;
                    
                    // 检查双击
                    long currentTime = System.currentTimeMillis();
                    if (currentTime - lastTapTime < DOUBLE_TAP_TIMEOUT) {
                        // 双击重置大小
                        params.width = DEFAULT_WIDTH;
                        params.height = DEFAULT_HEIGHT;
                        updateViewLayout();
                        lastTapTime = 0;
                        return true;
                    }
                    lastTapTime = currentTime;
                    
                    if (event.getX() > view.getWidth() - RESIZE_HANDLE_SIZE && 
                        event.getY() > view.getHeight() - RESIZE_HANDLE_SIZE) {
                        isMoving = false;
                    } else {
                        isMoving = true;
                    }
                    return true;

                case MotionEvent.ACTION_MOVE:
                    float deltaX = event.getRawX() - lastTouchX;
                    float deltaY = event.getRawY() - lastTouchY;
                    
                    // 检查是否超过最小移动阈值
                    if (!hasMoved && Math.abs(deltaX) < TOUCH_SLOP && Math.abs(deltaY) < TOUCH_SLOP) {
                        return true;
                    }
                    hasMoved = true;
                    
                    if (isMoving) {
                        // 计算新位置
                        int newX = initialX + (int) (event.getRawX() - initialTouchX);
                        int newY = initialY + (int) (event.getRawY() - initialTouchY);
                        
                        // 边界检查
                        params.x = Math.min(Math.max(0, newX), screenWidth - params.width);
                        params.y = Math.min(Math.max(0, newY), screenHeight - params.height);
                    } else {
                        // 调整大小
                        int newWidth = params.width + (int) deltaX;
                        int newHeight = params.height + (int) deltaY;
                        
                        // 限制尺寸范围并检查右边界
                        params.width = Math.min(Math.min(MAX_WIDTH, screenWidth - params.x), 
                                Math.max(MIN_WIDTH, newWidth));
                        params.height = Math.min(Math.min(MAX_HEIGHT, screenHeight - params.y), 
                                Math.max(MIN_HEIGHT, newHeight));

                        // 调整文字大小
                        int minDimension = Math.min(params.width, params.height);
                        float textSize = minDimension * 0.4f;
                        timeText.setTextSize(Math.min(50, Math.max(12, textSize)));
                    }
                    
                    updateViewLayout();
                    lastTouchX = event.getRawX();
                    lastTouchY = event.getRawY();
                    return true;

                case MotionEvent.ACTION_UP:
                    if (!hasMoved) {
                        // 如果没有移动，可以处理点击事件
                    }
                    lastTouchX = 0;
                    lastTouchY = 0;
                    return true;
            }
            return false;
        });

        windowManager.addView(overlayView, params);
        startTimeUpdate();
        updateColors();
    }

    private void updateViewLayout() {
        try {
            windowManager.updateViewLayout(overlayView, params);
        } catch (IllegalArgumentException e) {
            // 处理可能的异常
        }
    }

    private void startTimeUpdate() {
        if (timer != null) {
            timer.cancel();
        }
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    String currentTime = new SimpleDateFormat(timeFormat, Locale.getDefault())
                            .format(new Date());
                    if (overlayView != null) {
                        TextView timeText = overlayView.findViewById(R.id.overlayTimeText);
                        timeText.post(() -> {
                            if (timeText != null) {
                                timeText.setText(currentTime);
                            }
                        });
                    }
                } catch (IllegalArgumentException e) {
                    // 处理格式错误
                }
            }
        }, 0, 1000);
    }

    private void updateColors() {
        if (overlayView != null) {
            TextView timeText = overlayView.findViewById(R.id.overlayTimeText);
            if (timeText != null) {
                timeText.setTextColor(textColor);
                timeText.setBackgroundColor(Color.argb(
                        bgAlpha,
                        Color.red(bgColor),
                        Color.green(bgColor),
                        Color.blue(bgColor)
                ));
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        if (overlayView != null) {
            windowManager.removeView(overlayView);
        }
    }
} 